#include "threadPool.h"
#include "epoll.h"
#include "cmdFunc.h"

// 全局变量
const char *rootDir = "/home/netdisk/one/";
const char *log_addr="/home/netdisk/one/log/my_log";

int exitPipe[2];
void handler(int signum)
{
    printf("signum = %d\n",signum);
    write(exitPipe[1],"1",1);
}

// ./server ip prot workerNum
int main(int argc,char *argv[])
{
    ARGS_CHECK(argc,4);
    //启动服务端时检查网盘根目录是否存在（access），不存在则创建
    int ret = access(rootDir,F_OK|R_OK|W_OK|X_OK);
    if(ret == -1)
    {
        mkdir(rootDir,0777);
    }

    pipe(exitPipe);
    if(fork() != 0)
    {
        close(exitPipe[0]);
        signal(SIGUSR1,handler);
        wait(NULL);
        printf("Parent is going to exit\n");
        exit(0);
    }
    close(exitPipe[1]);
    threadPool_t threadPool;
    threadPoolInit(&threadPool,atoi(argv[3]));
    makeWorker(&threadPool);

    int sockfd;
    tcpInit(argv[1],argv[2],&sockfd);
    int epfd = epoll_create(1);
    epollAdd(epfd,sockfd);
    epollAdd(epfd,exitPipe[0]);
    while(1)
    {
        struct epoll_event readySet[1024];
        int readyNum = epoll_wait(epfd,readySet,1024,-1);
        for(int i = 0;i < readyNum;i++)
        {
            if(readySet[i].data.fd == sockfd)
            {
                int netfd = accept(sockfd,NULL,NULL);
                pthread_mutex_lock(&threadPool.mutex);
                enQueue(&threadPool.taskQueue,netfd);
                printf("i am main thread ,i send a netfd = %d\n",netfd);
                pthread_cond_signal(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
            }
            else
            {
                printf("threadPool is going to exit\n");
                pthread_mutex_lock(&threadPool.mutex);
                threadPool.exitFlag = 1;
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
                for(int i = 0;i < threadPool.tidArr.workerNum;i++)
                {
                    pthread_join(threadPool.tidArr.arr[i],NULL);
                }
                printf("main thread is going to exit\n");
                exit(0);
            }
        }
    }
    return 0;
}
